package com.csist.client;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class ClientSendThread implements Runnable{
	private Socket socket;
	private boolean state=true;
	private BufferedReader br=null;
	private DataOutputStream dos=null;
	
	public ClientSendThread(Socket socket){
		this.socket=socket;
		br=new BufferedReader(new InputStreamReader(System.in));
		try {
			dos=new DataOutputStream(this.socket.getOutputStream());
		} catch (IOException e) {
			close();
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		while(this.state){
			try {
				String message=br.readLine();
				if (message != null && message.trim().length() > 0) {
					send(message);
					if("886".equals(message)){
//						close();
						break;
					}
				}
			} catch (IOException e) {
				close();
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 发送消息
	 */
	public void send(String msg){
		try {
			dos.writeUTF(msg);//writeUTF(String str):以机器无关的方式使用utf-8编码方式将字符串写到基础输出流中
			dos.flush();
		} catch (IOException e) {
			close();
			e.printStackTrace();
		}
	}
	
	/**
	 * 释放资源
	 */
	public void close(){
		this.state=false;
		if(br!=null){
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		if(dos!=null){
			try {
				dos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(socket!=null){
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
